﻿#include "widget.h"
#include "ui_widget.h"
#include <QTreeWidgetItem>
#include <QSettings>
#include <QDebug>
#include <QFile>
#include <QStandardPaths>
#include <QDir>
#include <QFileInfo>
#include <QtWidgets>
#include <QAction>
#include "excelengine.h"
#include <QKeyEvent>
#include <QFileDialog>
#include <QFileInfo>
#include <QHeaderView>
#include <QVariant>
#include "ui/formsetting.h"
#include <QMap>
#include <QMapIterator>
//#include <QTcpSocket>
#include "loadingwidget.h"
#include "client/clientthread.h"
#include "excelthread.h"
#include <QSqlError>
#include <QSqlQuery>
#include <QPropertyAnimation>

#include "ui/formrecordcontrol.h"
#include "ui/formitemwidgetgroup.h"
#include "utils/winmanager.h"
#include "utils/gloweffect.h"

#include "jsonhelp.h"

#ifdef Q_OS_WIN
	#include <QtWin>
#endif
//#include <libxl.h>
//using namespace libxl;

#define SQLDATARECORDTBNAME "dataRecording"

Widget::Widget(QWidget *parent) :
	QWidget(parent),system_tray(NULL),preBtnPut(NULL),TimerGlbDly(NULL),_flagAppStartFirst(false),settingform(nullptr),_DlyGlobalTimeS(0),flagSortTable(false),
    menuImport(NULL),
	ui(new Ui::Widget)
{
	ui->setupUi(this);

	m_glbBoxnum.second = false;

	defaultSetting();
	set_ui();

    jsonHelp jshlp;
//    jshlp.insertGroup("group1");

	connect(this,&Widget::sigChangeBoxSort,this,&Widget::sltChangeBoxSort);

    connect(ui->btnSetting,&QToolButton::clicked,[=]{
        FormSetting *settingform = setupSettingForm(this);
        if(settingform)
            settingform->isHidden()?settingform->show():settingform->activateWindow();
    });

	//default timer to show current time
	QTimer *time = new QTimer(this);
	time->start(1000);
    connect(time,&QTimer::timeout,[=]{
        ui->states_group_timeSet->setText(QDateTime::currentDateTime().toString("yyyy-MM-dd hh:mm:ss"));
    });

	//todo .add copy of table
//    connect(ui->tableWidget,&QTableWidget::)

	if(_flagAppStartFirst){//程序第一次启动时弹出设置对话框
		setupSettingForm(this);
	}else{
		//NOTE:检测是否有分组记录,否也应弹出
		QSettings setting;
		setting.beginGroup("GroupData");
		if(!setting.childGroups().count())
			setupSettingForm(this);
		setting.endGroup();
		//end
	}

	//TODO:test for style.
	stylize(this->objectName(),this);

	//test-ODBC    
//    ExcelEngine *exl = new ExcelEngine(ExcelEngine::ReadWrite,QFileDialog::getOpenFileName());
//    exl->ReadDataSheetByODBC(QStringLiteral("投喂标准"));//投喂标准
//    QSqlDatabase db = QSqlDatabase::addDatabase("QODBC");
//    db.setDatabaseName(QString("Driver={Microsoft Excel Driver (*.xls, *.xlsx, *.xlsm, *.xlsb)};Readonly=0;DriverId=790;Dbq=%1;DefaultDir=e:\\").arg(
//                           QFileDialog::getOpenFileName()));//"e:\\fffontact.xlsx"
//    if ( db.open()){
//        QSqlQuery query;
//        query.exec("select * from [sheet1$]");
//        while (query.next()) {
//            QString title = query.value(0).toString();
//            QString author = query.value(1).toString();
//            QMessageBox::critical(0, title,author);
//            qDebug()<<query.value(0);
//        }
//        qDebug()<<"___"<<query.lastError()<<query.size();
//    }
//    qDebug()<<db.lastError();    

}

void Widget::defaultSetting()
{ //test...2014-08-23
//    QSettings setting(QStandardPaths::writableLocation(QStandardPaths::DataLocation)+"/data/config.ini",QSettings::IniFormat);

	QSettings setting;
	setting.beginGroup("GroupData");
    for(int i = 0;i<setting.childGroups().count();i++){
        QString strip = setting.value(QString("%1/IpAdd").arg(setting.childGroups().at(i)),i>9?QString("192.168.1.1%1").arg(i):QString("192.168.1.10%1").arg(i)).toString();
        ui->combGroup->addItem(QString::number(i+1));
        ui->combGroup->setItemData(i,strip);
    }
    setting.endGroup();
    ui->states_group_IPSet->setText(ui->combGroup->itemData(ui->combGroup->currentIndex()).toString());

    for(int i=0;i<ui->combGroup->count();i++){
        m_BarrelStatus.insert(ui->combGroup->itemText(i).toInt(),sendHead());
    }

	loadSetting();
}

void Widget::loadSetting()
{
	QSettings setting;
	setting.beginGroup("GroupData");
    for(int i = 0;i<setting.childGroups().count();i++){
        _GroupIpList.insert(i+1,setting.value(QString("%1/IpAdd").arg(i+1)).toString());
//        qDebug()<<"loadsetting:"<<i+1<<setting.value(QString("%1/IpAdd").arg(i+1)).toString();
    }
    setting.endGroup();

    //custom title.
    if(!setting.value("general/appTitle","").toString().isEmpty())
        setWindowTitle(setting.value("general/appTitle").toString());

	setting.beginGroup("AppData/Operate");
	_DlyGlobalTime = setting.value("DelayTime",300).toInt();
	_flagAppStartFirst = setting.value("FirstStart",true).toBool();
	setting.endGroup();

	//load the application geometry;
	restoreGeometry(setting.value("AppData/geometry",QByteArray()).toByteArray());

//    emit sendConnectSocket(QMap<int,QString>);
}

void Widget::saveSetting()
{

}

void Widget::initWndInfo(QWidget *wnd,GroupItemData itemdata)
{
    QVBoxLayout *mainlayout = new QVBoxLayout;
    QMapIterator<QString,QTime> itor(itemdata.getTBStartTimes());
    if(itemdata.getTBStartTimes().count()){
        while(itor.hasNext()){
            QHBoxLayout *itemlayout = new QHBoxLayout;
            itor.next();
            QLabel *lblitem = new QLabel(itor.key(),wnd);
            QLabel *lblstart = new QLabel(QString::fromLocal8Bit("投喂时间:%1").arg(itor.value().toString("hh:mm:ss")),wnd);
            itemlayout->addWidget(lblitem);
            itemlayout->addWidget(lblstart);
            QString lblstyleOut = QString("QLabel{color:lightgray;}");
            QString lblstyleCurrent = QString("QLabel{color:red;}");
            QString lblstyleNor = QString("QLabel{color:black;}");
            QTime currenttime = QTime(QDateTime::currentDateTime().time().hour(),QDateTime::currentDateTime().time().minute(),QDateTime::currentDateTime().time().second());
            QTime itorTime = itor.value();
            int interval = currenttime.msecsTo(itorTime);
            if(interval>0){
                if(itor.key().contains(itemdata.currentTable())){
                    lblitem->setStyleSheet(lblstyleCurrent);
                    lblstart->setStyleSheet(lblstyleCurrent);
                }else{
                    lblitem->setStyleSheet(lblstyleNor);
                    lblstart->setStyleSheet(lblstyleNor);
                }
            }else{
                lblitem->setStyleSheet(lblstyleOut);
                lblstart->setStyleSheet(lblstyleOut);
            }

            mainlayout->addLayout(itemlayout);
        }
    }else{
        mainlayout->addWidget(new QLabel(QStringLiteral("未开始"),wnd));
    }
    wnd->setLayout(mainlayout);
}

void Widget::set_ui()
{
    //delete all old widget of groupBox.
    foreach(QToolButton *btn,ui->groupBox->findChildren<QToolButton*>()){
        btn->deleteLater();
    }

    //init Home Page's button effect
    initHomeButton();

    //Default right side ibs not visible
    connect(ui->switchWin_Right,&QStackedWidget::currentChanged,[=]{
        if(ui->switchWin_Right->currentWidget() == ui->page_Right_Status){
            setMinimumWidth(1160);
            //load all group Button.
            foreach(QToolButton *btn,ui->groupBox->findChildren<QToolButton*>()){
                btn->deleteLater();
            }
            ui->groupBox->setTitle(QStringLiteral("预览"));

            QSettings setting;
            setting.beginGroup("GroupData");
            QMap<int,QString> maplist;
            foreach(QString str,setting.childGroups())
                maplist.insert(str.toInt(),str);
            int m_i = 0,m_j = 0;
            foreach(QString str,maplist){
                QToolButton *btn = new QToolButton(ui->page_Right_Status);
                btn->setObjectName(QString("%1-GroupStatus").arg(str));
                btn->setFixedSize(35,35);
                btn->setIconSize(QSize(16,16));
                btn->setToolButtonStyle(Qt::ToolButtonTextUnderIcon);
                btn->setText(str);
                ui->gridLayout_groupButton->addWidget(btn,m_i,m_j++);
                if(m_j == 6){
                    m_i++;
                    m_j = 0;
                }

                connect(btn,&QToolButton::clicked,[=]{
                    QTreeWidgetItem * item = NULL;
                    QString itemText("");
                    for(int i = 0;i<ui->treeWidget->topLevelItemCount();i++){
                        item  = ui->treeWidget->topLevelItem(i);
                        auto *item_widget = qobject_cast<FormItemWidgetGroup*>(ui->treeWidget->itemWidget(item,0));
                        if(item_widget){
                            itemText = item_widget->Data().getGroupNum();
                        }
                        if(itemText.isEmpty())
                            return;

                        if(btn->text().toInt() == itemText.toInt()){
                            //show info.;
                            QWidget *wndinfo = new QWidget(this);
                            wndinfo->setObjectName("wndinfo_rightside");
                            wndinfo->setAttribute(Qt::WA_DeleteOnClose);
                            wndinfo->setWindowFlags(wndinfo->windowFlags() | Qt::FramelessWindowHint | Qt::Popup);
                            wndinfo->setStyleSheet(QString("QWidget#%1{background-color:rgb(222,238,255);}").arg(wndinfo->objectName()));
                            FormRecordControl *rc_widget = qobject_cast<FormRecordControl*>(ui->treeWidget->itemWidget(item->child(0),0));
                            if(rc_widget){
                                initWndInfo(wndinfo,rc_widget->GroupData());
                            }
                            wndinfo->show();
                            wndinfo->move((QCursor::pos())+QPoint(-btn->width(),btn->height()/2));
                            break;
                        }
                    }
                });
            }
        }else setMinimumWidth(870);
        adjustSize();
    });

    //Defualt statck widget page is Page_home.
    ui->switchWin->setCurrentWidget(ui->page_Home);
    ui->switchWin_Right->setCurrentWidget(ui->page_Empty);
    ui->widget_RightSide->setVisible(false);
    setMinimumWidth(870);
    adjustSize();

	//ui property
	ui->tableWidget->horizontalHeader()->setSectionResizeMode(QHeaderView::Stretch);
	ui->tableWidget->verticalHeader()->setSectionResizeMode(QHeaderView::Stretch);
	ui->tableWidget->horizontalHeader()->resizeSections(QHeaderView::Stretch);
	ui->tableWidget->verticalHeader()->resizeSections(QHeaderView::Stretch);
	ui->tableWidget->installEventFilter(this);

    ui->pushButton_link->setEnabled(false);
    ui->pushButton_close->setEnabled(false);
    ui->pushButton_link->setText("");
    ui->pushButton_close->setText("");
    ui->pushButton_link->setStyleSheet("QPushButton{background:rgb(240,240,240,1);border-radius:2px;}");
    ui->pushButton_close->setStyleSheet("QPushButton{background:rgb(240,240,240,1);border-radius:2px;}");

    ui->combGroup->setEditable(true);
    ui->combGroup->setLineEdit(ui->groupLine);
    ui->pushButton_getinfo->setVisible(false);
    ui->btnGroupChange->setVisible(false);

//    ui->grpb_selectgroup->setAttribute(Qt::WA_TransparentForMouseEvents);
    ui->groupBoxStates->setAttribute(Qt::WA_TransparentForMouseEvents);
    ui->pushButton_link->setAttribute(Qt::WA_TransparentForMouseEvents);
    ui->pushButton_close->setAttribute(Qt::WA_TransparentForMouseEvents);

    menuImport = new QMenu(ui->btnImportExcel);
    ui->btnImportExcel->setMenu(menuImport);

//#ifdef USE_NEWVERSION
//    {
//        QAction *action = new QAction(ui->btnImportExcel);
//        action->setText(QStringLiteral("从数据文件夹中导入"));
//        menuImport->addAction(action);
//        connect(action,&QAction::triggered,[=]{
//            ImportData(true);
//        });

//        QAction *action2 = new QAction(ui->btnImportExcel);
//        action2->setText(QStringLiteral("从外部文件导入"));
//        action2->setToolTip(QStringLiteral("Excel文件导入"));
//        menuImport->addAction(action2);
//        connect(action2,&QAction::triggered,[=]{
//            ImportData(false);
//        });
//        QAction *action3 = new QAction(ui->btnImportExcel);
//        QSettings setting;
//        action3->setText(QStringLiteral("取消自动导入功能"));
//        action3->setToolTip(QStringLiteral("<p style='color:blue;'>自动导入可在设置面板中设置.</p>"));
//        action3->setEnabled(setting.value("general/DataImportHandle",QByteArray("-1")).toByteArray().toInt());
//        menuImport->addAction(action3);
//        connect(action3,&QAction::triggered,[=](bool){
//            QSettings setting;
//            setting.setValue("general/DataImportHandle",QByteArray("-1"));
//            action3->setEnabled(false);
////            ExportDataToExcelExists();
//        });

//        //Menu connect
//        connect(menuImport,&QMenu::aboutToShow,[=]{
//            if(m_BarrelStatus.find(ui->combGroup->currentText().toInt()) != m_BarrelStatus.end())
//            {
//                menuImport->setEnabled(m_BarrelStatus.find(ui->combGroup->currentText().toInt()).value().getPutweighTime().isNull());
//            }

//            if(menuImport)
//                foreach(auto action,menuImport->actions()){
//                    if(action->text() == QStringLiteral("取消自动导入功能"))
//                    {
//                        QSettings setting;
//                        int state = setting.value("general/DataImportHandle",QByteArray("-1")).toByteArray().toInt();
//                        if(state<0)
//                        {
//                            action->setEnabled(false);
//                            qDebug()<<state<<("12?");
//                        }else{
//                            action->setEnabled(true);
//                            qDebug()<<state<<("2?");
//                        }
//                        break;
//                    }
//                }
//        });
//    }

//    //Put weigh Menu.
//    QMenu *menuPutbtn = new QMenu(ui->pushButton_put);
//    QMenu *menuPutbtnDelay = new QMenu(QStringLiteral("延时放料"),ui->pushButton_put);
//    for(int i = 1;i<=3;i++)//TODO:setup the preDelay Time
//    {
//        QAction *action = new QAction(ui->pushButton_put);
//        action->setText(QString(QStringLiteral("延时 %1 (%2)放料")).arg(QString::number(i*5).toUtf8(),QStringLiteral("分钟")));
//        menuPutbtnDelay->addAction(action);
//        connect(action,&QAction::triggered,[=]{
//            QDateTime datetime = QDateTime(QDateTime::currentDateTime().date(),QTime(QDateTime::currentDateTime().toString("hh").toInt(),
//                                                                                     i*5 + QDateTime::currentDateTime().toString("mm").toInt(),
//                                                                                     QDateTime::currentDateTime().toString("ss").toInt()));
//            updateDlyTime(ui->combGroup->currentText().toInt(),datetime);//更新全局变量-延时计时时间
////			connect(this,&Widget::calcTimFinished,[=]
//            {
//                qDebug()<<QStringLiteral("延时放料..calcTimFinished..")<<datetime;
//                QTimer *timer = new QTimer(this);
//                timer->setProperty("customProperty_groupid",ui->combGroup->currentText().toInt());

//                if(_DlyGlobalTimeS){
//                    timer->start(_DlyGlobalTimeS*1000);
//                    ui->pushButton_put->setEnabled(false);
//                }
//                else {
//                    QMessageBox::information(0,"",QStringLiteral("延时时间设置有错，请重新设置"));
//                }

//                connect(timer,&QTimer::timeout,[=]{
//                    qDebug()<<QStringLiteral("计时结束:开始放料")<<timer->property("customProperty_groupid").toInt();
//                    //operate it.
//                    //NOTE:if timeout and the startPutOperate function's socket is not finished?do something....
//                    timer->stop();
//                    startPutOperate(timer->property("customProperty_groupid").toInt());
//                    timer->deleteLater();
//                });
//            }
////            );
//        });
//    }
//    menuPutbtnDelay->addAction(QStringLiteral("自定义放料时间"));
//    connect(menuPutbtnDelay->actions().last(),&QAction::triggered,[=]{
//        setupDelayPutWetTime();
//        connect(this,&Widget::sendCustomDlyTime,[=](QDateTime dlytime){
//            updateDlyTime(ui->combGroup->currentText().toInt(),dlytime);//更新全局变量-延时计时时间

////			connect(this,&Widget::calcTimFinished,[=]
//            {
//                QTimer *timer = new QTimer(this);
//                timer->setProperty("customProperty_groupid",ui->combGroup->currentText().toInt());
//                if(_DlyGlobalTimeS){
////                    ui->pushButton_put->setText(QStringLiteral("延时放料 剩余") + QString::number(_DlyGlobalTimeS) + QStringLiteral("秒"));
//                    timer->start(_DlyGlobalTimeS*1000);

//                    ui->pushButton_put->setEnabled(false);

////                    int caclTime = _DlyGlobalTimeS;
////                    QTimer *timercalc = new QTimer(this);
////                    timercalc->start(1000);
////                    connect(timercalc,&QTimer::timeout,[&](caclTime){
////                        if(caclTime<1){
////                            ui->pushButton_put->setText(QStringLiteral("放料"));
////                            timercalc->stop();
////                            timercalc->deleteLater();
////                        }
////                        ui->pushButton_put->setText(QStringLiteral("延时放料 剩余") + caclTime + QStringLiteral("秒"));
////                        caclTime--;
////                    });

//                }
//                else {
//                    QMessageBox::information(0,"",QStringLiteral("延时时间设置有错，请重新设置"));
//                }

//                connect(timer,&QTimer::timeout,[=]{
//                    //operate it.
//                    //NOTE:if timeout and the startPutOperate function's socket is not finished?
//                    timer->stop();
//    qDebug()<<QStringLiteral("计时结束:开始放料")<<timer->property("customProperty_groupid").toInt();

//                    startPutOperate(timer->property("customProperty_groupid").toInt());
//                    timer->deleteLater();
//                });
//            }
////            );
//        });
//    });
//    menuPutbtn->addAction(QStringLiteral("直接放料(不延时)"));
//    connect(menuPutbtn->actions().first(),&QAction::triggered,[=]{
//        startPutOperate(ui->combGroup->currentText().toInt());
//    });

//    menuPutbtn->addMenu(menuPutbtnDelay);
//    //menuPutbtnDelay->setEnabled(false);
//    ui->pushButton_put->setMenu(menuPutbtn);

    ui->groupLine->setAlignment(Qt::AlignCenter);
    connect(ui->groupLine,&QLineEdit::textChanged,[=](const QString & text){//切换组号时触发信号-检测当前组号IP连接状态，连接正常则启用按钮;
        ui->grpb_selectgroup->setTitle(QStringLiteral("分组")+QString("%1").arg(text));
        //var _flagConnected is true;
//        bool _flagConnected = false;//NOTE:global var
//        //setting the ui widget to use
//        bool flag = true;
//        QSettings setting;
//        setting.beginGroup("GroupData");
//        flag = setting.value(QString("%1/States").arg(text)).toBool();
//        setting.endGroup();
//        if(flag){
//            ui->pushButton_getinfo->setEnabled(!flag);
//            ui->pushButton_close->setEnabled(flag);
//            ui->pushButton_weigh->setEnabled(!flag);
//            ui->pushButton_link->setEnabled(!flag);
//            ui->pushButton_put->setEnabled(!flag);
//        }
    });

    ui->groupLine->setText(QStringLiteral("1"));
    ui->pushButton_put->setEnabled(false);//TODO:should be false.just for test!
    ui->pushButton_weigh->setEnabled(!ui->pushButton_put->isEnabled());//TODO:should be false.just for test!
    ui->cbImportExcel->setVisible(false);

    //TopWidget Btn next Group and PreGroup
    connect(ui->btnGroupNext,&QToolButton::clicked,[=]{
        if(ui->combGroup->currentText().toInt()<ui->combGroup->count()){
            ui->combGroup->setCurrentIndex(ui->combGroup->currentIndex()+1);
        }
    });
    connect(ui->btnGroupPre,&QToolButton::clicked,[=]{
        if(ui->combGroup->currentText().toInt()>1){
            ui->combGroup->setCurrentIndex(ui->combGroup->currentIndex()-1);
        }
    });

    connect(ui->cbImportExcel,&QCheckBox::stateChanged,[=](int state){
        ui->btnImportExcel->setEnabled(!state);
    });

    connect(ui->combGroup,&QComboBox::currentTextChanged,this,&Widget::sltcbGrpChange);

    connect(this,&Widget::updateGroupData,[=]{
        QStringList strlisofBox = QStringList();
        if(m_BarrelStatus.find(ui->combGroup->currentText().toInt()) != m_BarrelStatus.end())
            strlisofBox = m_BarrelStatus.find(ui->combGroup->currentText().toInt()).value().getBoxValueList();

        setupTableItem(strlisofBox);//初始化表格為默認
        //更新Combobox數據
        ui->combGroup->clear();
        QSettings setting;
        if(!setting.value("general/appTitle","").toString().isEmpty())
            setWindowTitle(setting.value("general/appTitle","").toString());

        setting.beginGroup("GroupData");
        for(int i = 0;i<setting.childGroups().count();i++){
            QString strip = setting.value(QString("%1/IpAdd").arg(setting.childGroups().at(i)),i>9?QString("192.168.1.1%1").arg(i):QString("192.168.1.10%1").arg(i)).toString();
            ui->combGroup->addItem(QString::number(i+1));
            ui->combGroup->setItemData(i,strip);
        }
        setting.endGroup();

        ui->states_group_IPSet->setText(ui->combGroup->itemData(ui->combGroup->currentIndex()).toString());
    });

    connect(ui->btnImportExcel,&QToolButton::clicked,[=]{
//        int state_DateImport;
//        QSettings setting;
//        state_DateImport = setting.value("general/DataImportHandle",QByteArray("-1")).toByteArray().toInt();
//        switch(state_DateImport){
//        case 0://手动导入--手动打开excel表进行导入
//            ImportData(false);
//            break;
//        case -1:
//            ui->btnImportExcel->showMenu();
//            break;
//        default://自动导入--从数据目录里自动获取数据导入
//            ImportData(true);
//            break;
//        }
        //Just show the menu.not handle data.
        ui->btnImportExcel->showMenu();
    });

	//Table property setting
	ui->tableWidget->verticalHeader()->setVisible(false);
	ui->tableWidget->setItemDelegateForColumn(0,new ReadOnlyDelegate(this));
	ui->tableWidget->setItemDelegateForColumn(2,new ReadOnlyDelegate(this));

	setupTableItem();

	for(int i=0;i<24;i++)
	{
		err[i]=true;
	}
	flag=false;

//	client_tcp=new QTcpSocket(this);
//	if(connectDB()){
//	   this->setWindowTitle(QStringLiteral("连接数据库成功"));
//	}else{
//	   QMessageBox::warning(this, "连接数据空失败", "请检查数据库文件", QMessageBox::Ok, QMessageBox::Ok);
//	}

	//Tray
	system_tray = new QSystemTrayIcon();
	system_tray ->setToolTip(QApplication::applicationName());
	system_tray ->setIcon(QIcon(":/res/global/app.png"));
	QMenu *menu = new QMenu();
	menu->addAction(QStringLiteral("显示主界面(&s)"),this,SLOT(showNormal()));
	QAction *actionSetting = new QAction(this);
	actionSetting->setText(QStringLiteral("设置面板(&P)"));
	connect(actionSetting,&QAction::triggered,[=]{
		setupSettingForm(this);
	});
	menu->addAction(actionSetting);
	menu->addSeparator();
	QAction *actionclose = new QAction(this);
	actionclose->setText(QStringLiteral("退出(&x)"));
	connect(actionclose,&QAction::triggered,[=]{
		FormSetting *settingform = qApp->findChild<FormSetting*>("settingForm_");
		if(settingform)
			if(!settingform->isHidden())
				settingform->close();
		qApp->quit();
	});
	menu->addAction(actionclose);

	system_tray->setContextMenu(menu);
	system_tray->setVisible(true);
	system_tray->show();
	connect(system_tray ,&QSystemTrayIcon::activated,[=](QSystemTrayIcon::ActivationReason reason){
		switch(reason)
		{//点击托盘显示窗口
		case QSystemTrayIcon::Trigger:
		{
			showNormal();
			break;
		}
		case QSystemTrayIcon::DoubleClick://双击托盘显示窗口
		{
			showNormal();
			break;
		}
		default:
			break;
		}

	});

	connect(ui->tableWidget,SIGNAL(itemChanged(QTableWidgetItem*)),this,SLOT(Weigh_item_cheack(QTableWidgetItem*)));
	connect(ui->tableWidget,&QTableWidget::cellChanged,[=](int row,int column){
		this->sltcbTblCellChange(row,column);
	});

    QShortcut *quitShortcut = new QShortcut(QKeySequence::Copy, ui->tableWidget);
    connect(quitShortcut, &QShortcut::activated, [=]{
        this->copyTable();
    });
//    connect(ui->tableWidget,&QTableWidget.setContextMenuPolicy();)

	//connect(client_tcp,SIGNAL(readyRead()),this,SLOT(display()));
//    if(client_tcp)
//    {
//        connect(client_tcp,SIGNAL(readyRead()),this,SLOT(recv_data()));
//        connect(client_tcp,SIGNAL(connected()),this,SLOT(connect_Successful()));
//        connect(client_tcp,SIGNAL(disconnected()),this,SLOT(connect_Close()));
//    }

//    return;
	//connect slot and signal


    connect(ui->pushButton_link,&QPushButton::clicked,[=]{
        //test ->TODO:delete this line
        connect(this,SIGNAL(sendConnectSocketReturn(int,bool)),this,SLOT(finishedConnectSlot(int ,bool)));
        ui->pushButton_link->setEnabled(false);
//        ui->pushButton_put->setEnabled(true);//TODO:should check has data in table...
//        ui->pushButton_weigh->setEnabled(false);
        ui->pushButton_weigh->setEnabled(true);//TODO:test to change true.should be delete;
        emit sendConnectSocket(_GroupIpList);
        emit sendConnectSocketReturn(ui->combGroup->currentText().toInt(),true);
    });

    connect(ui->pushButton_close,&QPushButton::clicked,[=]{
        QSettings setting;//将对应每一项当前连接状态保存到setting里，以便后面读取及更新界面UI
        setting.beginGroup(QString("GroupData/%1").arg(ui->combGroup->currentText()));
        setting.setValue("States",flag);//此处只保存当前组号连接状态
        setting.sync();//立即更新以保存
        setting.endGroup();
        ui->pushButton_link->setEnabled(true);
        ui->pushButton_close->setEnabled(false);
        ui->pushButton_put->setEnabled(false);
        ui->pushButton_weigh->setEnabled(false);
        emit closeConnect();
    });
}



Widget::~Widget()
{
//	if(menuImport){
//		delete menuImport;
//		menuImport = NULL;
//	}
//	if(TimerGlbDly){
//		if(TimerGlbDly->isActive())
//			TimerGlbDly->stop();
//		delete TimerGlbDly;
//		TimerGlbDly = NULL;
//	}
//	if(system_tray){
//		delete system_tray;
//		system_tray = NULL;
//	}
	delete ui;
}

void Widget::finishedConnectSlot(int groupid, bool flag)
{
    if(groupid == ui->combGroup->currentText().toInt() && flag)
        ui->pushButton_close->setEnabled(true);
    //TODO:update ui and enable it.
    QSettings setting;//将对应每一项当前连接状态保存到setting里，以便后面读取及更新界面UI
    setting.beginGroup(QString("GroupData/%1").arg(QString::number(groupid)));
    setting.setValue("States",flag);//此处只保存当前组号连接状态
    setting.sync();//立即更新以保存
    setting.endGroup();

    //Export to Excel
    ExportDataToExcelExists(groupid);
}

void Widget::finishedPutWeigh(int group, send_head realput)
{
//    ui->states_group_stateSet->setText(QStringLiteral("称量完成"));

	bool flag = false;
	QMap<int,QString> m_data_reale;
	if(group == ui->combGroup->currentText().toInt()){//判断是否为当前分组，若不是则只进行数据储存
		for(int i = 0;i<24;i++){
			float realputweigh=(realput.data[i]) * 0.01 ;
//			QTableWidgetItem *item = new QTableWidgetItem(QString::number(realputweigh));
//			item->setTextAlignment(Qt::AlignCenter);
//			m_data_reale.insert(i+1,item->text());
			m_data_reale.insert(i+1,QString::number(realputweigh));
//qDebug()<<"finishedPutWeigh:"<<realput.data[i]*0.01<<item->text();
//            ui->tableWidget->setItem(i,2,item);
//            tmp_sd.m_data.insert(i+1,realput.data[i]);
		}
		flag = true;
	}

	for(int i = 0;i<ui->tableWidget->rowCount();i++){
		if(m_data_reale.find(ui->tableWidget->item(i,0)->text().toInt()) != m_data_reale.end())
			ui->tableWidget->setItem(i,2,new QTableWidgetItem(m_data_reale.find(ui->tableWidget->item(i,0)->text().toInt()).value()));
		else ui->tableWidget->setItem(i,2,new QTableWidgetItem("-"));
		ui->tableWidget->item(i,2)->setTextAlignment(Qt::AlignCenter);
	}

	QMap<int,sendHead>::const_iterator itor = m_BarrelStatus.find(group);
	sendHead shtmp;
	if(itor != m_BarrelStatus.end()){
		shtmp = itor.value();
		shtmp.insertReale(m_data_reale);
		m_BarrelStatus.insert(group,shtmp);
//        shtmp.cleanDataOfPutweigh();
	}

	ui->pushButton_weigh->setEnabled(false);
	ui->pushButton_put->setEnabled(true);

    checkItemValue();
}

void Widget::checkItemValue()
{
//    ui->tableWidget->setSelectionBehavior(QAbstractItemView::SelectRows);
	ui->tableWidget->clearSelection();
	for(int i=0;i<24;i++)
	{
		bool flag = false;
		int type = -1;
		int value_entf = ui->tableWidget->item(i,1)->text().toFloat()*100;
		int value_ents = ui->tableWidget->item(i,2)->text().toFloat()*100;
		if(QString::number(value_ents).toInt() - QString::number(value_entf).toInt()>9)
		{
			flag = true;
			type = 1;
		}
		if( value_ents < value_entf)
		{
			flag = true;
			type = 2;
		}

		if(ui->tableWidget->item(i,1)->text().toLongLong() >= 0xffffffff)
		{
			flag = true;
			QTableWidgetItem *item = new QTableWidgetItem(ui->tableWidget->item(i,2)->text() + QStringLiteral("(离线了)"));
			ui->tableWidget->setItem(i,2,item);
			type = 3;
		}

		if(flag){
			for(int j=0;j<3;j++){
				ui->tableWidget->item(i,j)->setBackgroundColor(Qt::red);
				ui->tableWidget->item(i,j)->setForeground(Qt::white);
			}
			switch(type){
			case 1:
				ui->tableWidget->item(i,1)->setBackgroundColor(QColor(90,148,206));
				ui->tableWidget->item(i,2)->setBackgroundColor(QColor(90,148,206));
				break;
			case 2:
				ui->tableWidget->item(i,1)->setBackgroundColor(Qt::green);
				ui->tableWidget->item(i,2)->setBackgroundColor(Qt::green);

				break;
			case 3:
				ui->tableWidget->item(i,2)->setBackgroundColor(QColor(128,0,128));

				break;
			}
		}
	}
}

void Widget::sltChangeBoxSort(QStringList strlist)
{
	flagSortTable = true;
 qDebug()<<strlist<<"sltChangeBoxSort......";
 //NOTE:must after the field of last field is ok.
//    ui->tableWidget->setSortingEnabled(true);
//    ui->tableWidget->sortByColumn(0);
	QMap<int,QStringList> listrow;
	for(int i = 0;i<ui->tableWidget->rowCount();i++){
		QStringList listvalue;
		for(int j=1;j<ui->tableWidget->columnCount();j++){
			listvalue.append(ui->tableWidget->item(i,j)->text());
		}
		listrow.insert(ui->tableWidget->item(i,0)->text().toInt(),listvalue);
	}

	//sort
	QTableWidgetItem * itemf,*items;
	for(int i = 0;i<ui->tableWidget->rowCount();i++){
		QString findstr = strlist.count()>0? strlist.at(i):"";
		QMap<int,QStringList>::const_iterator itor = listrow.find(findstr.isEmpty()?-1:findstr.toInt());
		if(itor != listrow.end())\
		{
			itemf = new QTableWidgetItem(itor.value().at(0));
			items = new QTableWidgetItem(itor.value().at(1));
		}
		else
		{
			itemf = new QTableWidgetItem("0");
			items = new QTableWidgetItem("0");
		}
		itemf->setTextAlignment(Qt::AlignCenter);
		items->setTextAlignment(Qt::AlignCenter);

		ui->tableWidget->setItem(i,0,new QTableWidgetItem(QString::number(findstr.isEmpty()?i+1:findstr.toInt())));
		ui->tableWidget->item(i,0)->setTextAlignment(Qt::AlignCenter);
		ui->tableWidget->setItem(i,1,itemf);
		ui->tableWidget->setItem(i,2,items);
	}
	m_glbBoxnum.first = strlist;
	m_glbBoxnum.second = true;
    flagSortTable = false;
}

void Widget::copyTable(int column)
{
    QString copystr;
//    if(ui->tableWidget->selectedItems().count()<2)
    {
        ui->tableWidget->selectColumn(column);
        for(int i = 0;i<ui->tableWidget->rowCount();i++){
            copystr.append(ui->tableWidget->item(i,column)->text() + "\n");
		}
	}
//    else{
//        for(int i = 0;i<ui->tableWidget->rowCount();i++){
//            for(int j = 0;j<ui->tableWidget->columnCount();j++){
//                if(ui->tableWidget->item(i,j)->isSelected())
//                {
//                    copystr.append(ui->tableWidget->item(i,j)->text());
//                }else
//                    copystr.append("");
//                copystr.append("\t");
//            }
//            copystr.append("\n");
//        }
//    }
    QApplication::clipboard()->setText(copystr);
}

void Widget::on_pushButton_weigh_clicked()
{
	if(ui->pushButton_put->isEnabled())
		ui->pushButton_put->setEnabled(false);

	connect(this,SIGNAL(sendGroupPutWeithInfo(int,send_head)),this,SLOT(finishedPutWeigh(int,send_head)));//TODO:test...delete..
//	ui->states_group_stateSet->setText(QStringLiteral("称量中..."));

	ui->pushButton_weigh->setEnabled(false);

	//Test.TODO:
	QTcpSocket *socket = new QTcpSocket(this);
	socket->connectToHost(ui->states_group_IPSet->text(),5000);
//    socket->connectToHost("localhost",5000);//TODO.test. delete
	tcpSocketHash.insert(ui->combGroup->currentText().toInt(),socket);
//    recv_data();
	connect(socket,&QTcpSocket::connected,[=]{
		struct send_head buf;
		memset(&buf,0,sizeof(buf));
		buf.head=0xbb;
		buf.cmd=0xff;
		QMap<int,sendHead>::const_iterator itor = m_BarrelStatus.find(ui->combGroup->currentText().toInt());
		if(itor != m_BarrelStatus.end()){
			for(int i=0;i<24;i++){
				QMap<int,quint32>::const_iterator itor_b = itor.value().m_data_barrel.find(i+1);
				if(itor_b != itor.value().m_data_barrel.end())
					buf.data[itor_b.key()-1] = itor_b.value();
				else buf.data[itor_b.key()] = 0;

qDebug()<<"send to server:data:"<<buf.data[itor_b.key()];

				itor_b++;
			}
			buf.fcc=GetCheckSum(&buf,sizeof(buf)-sizeof(quint32));
			socket->write(QByteArray::fromRawData((char *)&buf,sizeof(buf)));
		}
	});

	connect(socket,&QTcpSocket::readyRead,[=]{
		//get return data.
		QByteArray recv_bufbyte=socket->readAll();
		qDebug()<<QStringLiteral("接收到的数据")<<recv_bufbyte.toHex();
		struct send_head *recv;
		recv=(struct send_head *)recv_bufbyte.data()+recv_bufbyte.indexOf(0xbb);

		emit sendGroupPutWeithInfo(ui->combGroup->currentText().toInt(),*recv);
		socket->disconnectFromHost();//just for single thread...
		socket->waitForDisconnected(500);
		socket->deleteLater();
	});
	if(!socket->waitForConnected(1000)){
		QMessageBox::information(0,QStringLiteral("提示"),QStringLiteral("网络连接失败，请检查IP地址是否正确."));
		ui->pushButton_weigh->setEnabled(true);
	}

}

void Widget::on_pushButton_link_clicked()
{

	emit sendConnectSocket(_GroupIpList);
}

void Widget::on_pushButton_put_clicked()
{
	ui->pushButton_put->showMenu();
//    emit sendGroupBatchInfo(ui->combGroup->currentText().toInt());
}

void Widget::updateDlyTimeSave()
{
//	_DlyGlobalTime = time;
    qDebug()<<"updateDlyTimeSave";
	QSettings setting;
	setting.beginGroup("AppData/Operate");
	setting.setValue("DelayTime",_DlyGlobalTimeS);
	setting.endGroup();
	emit calcTimFinished();
}

void Widget::updateDlyTime(int groupid,QDateTime datetime)
{
    if(m_BarrelStatus.find(groupid) != m_BarrelStatus.end())
        m_BarrelStatus.find(groupid).value().setPutweighTime(datetime);

    _DlyGlobalTimeS = abs((datetime.toString("hh").toInt() - QDateTime::currentDateTime().toString("hh").toInt())*3600 +
			(datetime.toString("mm").toInt() - QDateTime::currentDateTime().toString("mm").toInt())*60 +
             datetime.toString("ss").toInt() - QDateTime::currentDateTime().toString("ss").toInt());

qDebug()<<"DelayTime to MSecsSinceEpoch"<<_DlyGlobalTimeS<<datetime;

    ui->pushButton_put->setEnabled(false);

	if(datetime < QDateTime::currentDateTime())
		_DlyGlobalTimeS = 0;
	else
		ui->states_group_timeSet_Remain->setText(datetime.toString("yyyy-MM-dd hh:mm:ss"));
	updateDlyTimeSave();
}

FormSetting *Widget::setupSettingForm(QWidget *parent)
{
	FormSetting *settingform = NULL;
	settingform = qApp->findChild<FormSetting*>("settingForm_");

	if(!settingform){
//        settingform = new FormSetting(_GroupIpList,qobject_cast<QWidget*>(this->parent()));
		settingform = new FormSetting(_GroupIpList,parent);
		settingform->setWindowFlags(Qt::Dialog /*| Qt::FramelessWindowHint*/);
		settingform->setObjectName("settingForm_");
		settingform->setWindowOpacity(0.94);
//        settingform->setStyleSheet(QString("QWidget#%1{background-color:rgba(40,77,106,250);}").arg(settingform->objectName()));
        connect(settingform,&FormSetting::onClose,[=](bool,QMap<int,QString>m_mapGroupIp){
            _GroupIpList = m_mapGroupIp;

//            if(flag)
//				emit updateGroupData();
            emit WinMgr.sig_changIP();
		});
//        connect(this,&Widget::onCloseWidget,[=]{
//            settingform->close();
//        });
		settingform->show();
		settingform->activateWindow();
	}
    return settingform;
}

void Widget::setupDelayPutWetTime()//设置自定放料时间对话框部件初始化
{
	QHBoxLayout *hbox = new QHBoxLayout;
	QVBoxLayout *vbox = new QVBoxLayout;
	QHBoxLayout *hbox_btn = new QHBoxLayout;
	QHBoxLayout *hbox_txt = new QHBoxLayout;
	QWidget *widget_put = new QWidget(NULL);
	widget_put->setWindowModality(Qt::ApplicationModal);
	widget_put->setAttribute(Qt::WA_DeleteOnClose);
	QLineEdit* dlytimeLine = new QLineEdit(widget_put);
	QLabel* lblTips = new QLabel(widget_put);
	QToolButton* btnok = new QToolButton(widget_put);
	QToolButton* btncancel = new QToolButton(widget_put);

	dlytimeLine->setVisible(false);
	QDateTimeEdit  *datetime = new QDateTimeEdit(widget_put);
	datetime->setCalendarPopup(true);
	datetime->setDisplayFormat("yyyy.MM.dd hh:mm:ss");
	datetime->setDateTime(QDateTime::currentDateTime());

	hbox_txt->addWidget(lblTips);
//    hbox_txt->addWidget(dlytimeLine);
	hbox_txt->addWidget(datetime);
	hbox_btn->addWidget(btnok);
	hbox_btn->addWidget(btncancel);
	vbox->addLayout(hbox_txt);
	vbox->addLayout(hbox_btn);
	hbox->addLayout(vbox);
	widget_put->setLayout(hbox);

	lblTips->setText(QStringLiteral("输入延时时间(单位:ms)"));
	btnok->setText(QStringLiteral("确定"));
	btncancel->setText(QStringLiteral("取消"));
	widget_put->show();
	widget_put->move(ui->pushButton_put->pos()+this->pos()-QPoint(widget_put->width(),widget_put->height()));
	connect(btnok,&QToolButton::clicked,[=]{
		//TODO:Set a global Var to change the time to delay.
//        emit sendCustomDlyTime(dlytimeLine->text().toInt());
		emit sendCustomDlyTime(datetime->dateTime());
		widget_put->close();
	});
	connect(btncancel,&QToolButton::clicked,[=]{//Do Nothing
		widget_put->close();
	});
}

void Widget::setupTableItem(QStringList boxnumList)
{
	/*初始化桶号的列*/
	for(int r = 0;r<24;r++){
		for(int c=0;c<ui->tableWidget->horizontalHeader()->count();c++){
			item = new QTableWidgetItem();
			QString text = "";
			QMap<int,sendHead>::const_iterator itor = m_BarrelStatus.find(ui->combGroup->currentText().toInt());
			switch (c){
			case 0://列1
//                if(!m_glbBoxnum.second)
//                    text = QString::number(r+1);
//                else text = m_glbBoxnum.first.count()?m_glbBoxnum.first.at(r):QString::number(r+1);
                if(boxnumList.isEmpty())
					text = QString::number(r+1);
                else text = boxnumList.count()?boxnumList.at(r):QString::number(r+1);
				break;
			case 1:{//列2-如果未称量，则还原原有数据
				//TODO:find map value should check it is ok.
				if(itor != m_BarrelStatus.end()){
					int findvalue = ui->tableWidget->item(r,0)->text().toInt();
					if(!itor.value().m_hadBarrel)
						text = "";
					else{
						QMap<int,quint32>::const_iterator itorBarrel = itor.value().m_data_barrel.find(findvalue);
						if(itorBarrel != itor.value().m_data_barrel.end())
							text = QString::number(QString::number(itorBarrel.value()).toDouble() * 0.01);
						text == "0"?text="":text;
					}
				}
				break;
			}
			case 2:{//列3
				if(itor != m_BarrelStatus.end()){
					int findvalue = ui->tableWidget->item(r,0)->text().toInt();
					QMap<int,quint32>::const_iterator itorReal = itor.value().m_data_reale.find(findvalue);
					if(itorReal != itor.value().m_data_reale.end() && itor.value().m_hadPutweigh){
						text = QString::number(QString::number(itorReal.value()).toDouble() * 0.01 );
					}else text = "0";
				}
			}
				break;
			}
			item->setText(text);
			item->setTextAlignment(Qt::AlignCenter);
			ui->tableWidget->setItem(r,c,item);
		}
	}
}

void Widget::startPutOperate(int groupid)
{
	if(groupid<0){
		qDebug()<<__LINE__<<__FUNCTION__<<"groupid is invaild."<<groupid;
		return;
	}

	//IP
	QMap<int,QString>::const_iterator itor_ip = _GroupIpList.find(groupid);
    if(itor_ip != _GroupIpList.end())
    {
        if(!ui->pushButton_weigh->isEnabled())
            ui->pushButton_weigh->setEnabled(true);
        {
            qDebug()<<__LINE__<<__FUNCTION__<<"groupid:"<<groupid;

            ClientThread *clientThread = new ClientThread(/*groupid,itor_ip.value()*/);// (groupid,itor_ip.value());
            //! replace thread way.
            //! 1
            connect(clientThread,&ClientThread::sig_finishedPutWeigh,[=]{
                ui->states_group_timeSet_Remain->setText(("0000-00-00 00:00:00"));
                ui->states_group_stateSet->setText(QStringLiteral("放料完成"));

                ui->pushButton_weigh->setEnabled(true);
                ui->pushButton_put->setEnabled(false);

                QSettings setting;
                QString pathparent = setting.value("general/DefaultSaveDir",QStandardPaths::writableLocation(QStandardPaths::DataLocation)).toString();
                QDir dirParent(pathparent + QDir::separator() + QString::number(groupid));

                dirParent.setFilter(QDir::Files|QDir::NoDotAndDotDot);
                QFileInfoList list = dirParent.entryInfoList();
                int i=list.count();

                qDebug()<<QStringLiteral("开始写入Excel文件到:")<<i<<dirParent.absolutePath()<<pathparent;//TODO：check the dirparent value.

                while(i){
                    QFileInfo fileInfo = list.at(i-1);
                    QString fileBaseName = fileInfo.fileName();

                    //                    bool isFile_dat = fileInfo.fileName().endsWith(".xlsx") ||
                    //							fileInfo.fileName().endsWith(".xls");
                    qDebug()<<QStringLiteral("Excel writing...:")<<dirParent.absoluteFilePath(fileInfo.fileName());
                    //					if (isFile_dat)
                    {
                        fileBaseName=fileInfo.baseName();

                        //Qmap of value
                        QMap<int, sendHead>::const_iterator itor = m_BarrelStatus.find(groupid);

                        if(itor != m_BarrelStatus.end()){
                            QDir dirrecord(dirParent.absolutePath() + QDir::separator() + QStringLiteral("投料记录"));
                            if(!dirrecord.exists())
                                dirrecord.mkpath(dirrecord.absolutePath());
                            QString var = QString("yyyy-MM-dd_hh%1mm%2ss%3");
                            var = var.arg(QStringLiteral("时"),QStringLiteral("分"),QStringLiteral("秒"));
                            QFile file(dirrecord.absoluteFilePath(QDateTime::currentDateTime().toString(var) + ".txt"));
                            file.open(QIODevice::WriteOnly | QIODevice::Text);

                            QStringList listboxnum = itor.value().valueOfBoxnum;
                            for(int itt = 0;itt<24;itt++)
                            {
                                QMap<int,quint32>::const_iterator it = itor.value().m_data_reale.find(listboxnum.count()>itt?listboxnum.at(itt).toInt():
                                                                                                                             ui->tableWidget->item(itt,0)->text().toInt());
                                QString value = "0";
                                if(it != itor.value().m_data_reale.end())
                                {
                                    value = QString::number(QString::number(it.value()).toDouble() * 0.01);
                                    //                                    tmpmap.insert(itt+1,value);
                                }
                                file.write(value.toLatin1().data());
                                file.write("\n");
                            }
                            file.close();
                            //                            threadexlsR->setWriteDate(tmpmap);
                        }
                        //						threadexlsR->start();
                        break;//NOTE:just match first one.
                    }
                    i--;
                }

                QMap<int,sendHead>::const_iterator itor = m_BarrelStatus.find(groupid);
                sendHead shtmp;
                if(itor != m_BarrelStatus.end()){
                    shtmp = itor.value();
                    shtmp.cleanDataOfBarrel();
                    shtmp.cleanDataOfPutweigh();
                    m_BarrelStatus.insert(groupid,shtmp);
                    qDebug()<<"...from serve."<<m_BarrelStatus.find(groupid).value().m_data_barrel.find(1).value();
                    //				}
                    qDebug()<<"put weigh success.Get return value from serve.";//<<recv->cmd;

                    //if not the current.
                    if(groupid == ui->combGroup->currentText().toInt())
                        setupTableItem(m_BarrelStatus.find(groupid).value().getBoxValueList());
                }
                clientThread->deleteLater();
            });
            clientThread->start();
            //! 1 end.
//            socket->moveToThread(thread);
//            thread->start();
//            socket->connectToHost(itor_ip.value(),5000);
//            connect(socket,&QTcpSocket::connected,[=]{
//                struct send_head buf;
//                memset(&buf,0,sizeof(buf));
//                buf.head=0xbb;
//                buf.cmd=0x0f;
//                for(int i=0;i<24;i++){
//                   buf.data[i] = 0xffffffff;
//                }
//                buf.fcc=GetCheckSum(&buf,sizeof(buf)-sizeof(quint32));
//                socket->write(QByteArray::fromRawData((char *)&buf,sizeof(buf)));
//qDebug()<<"put weigh connected success.start write data.";
//            });

//            connect(socket,&QTcpSocket::readyRead,[=]{
//                ui->states_group_timeSet_Remain->setText(("0000-00-00 00:00:00"));
//                ui->states_group_stateSet->setText(QStringLiteral("放料完成"));

//                ui->pushButton_weigh->setEnabled(true);
//                ui->pushButton_put->setEnabled(false);

//                QSettings setting;
//                QString pathparent = setting.value("general/DefaultSaveDir",QStandardPaths::writableLocation(QStandardPaths::DataLocation)).toString();
//                QDir dirParent(pathparent + QDir::separator() + QString::number(groupid));

//                dirParent.setFilter(QDir::Files|QDir::NoDotAndDotDot);
//                QFileInfoList list = dirParent.entryInfoList();
//                int i=list.count();

//                qDebug()<<QStringLiteral("开始写入Excel文件到:")<<i<<dirParent.absolutePath()<<pathparent;//TODO：check the dirparent value.

//                while(i){
//                    QFileInfo fileInfo = list.at(i-1);
//                    QString fileBaseName = fileInfo.fileName();

//                    //                    bool isFile_dat = fileInfo.fileName().endsWith(".xlsx") ||
//                    //							fileInfo.fileName().endsWith(".xls");
//                    qDebug()<<QStringLiteral("Excel writing...:")<<dirParent.absoluteFilePath(fileInfo.fileName());
//                    //					if (isFile_dat)
//                    {
//                        fileBaseName=fileInfo.baseName();

//                        //Qmap of value
//                        QMap<int, sendHead>::const_iterator itor = m_BarrelStatus.find(groupid);

//                        //						ExcelThread *threadexlsR = new ExcelThread(dirParent.absoluteFilePath(fileInfo.fileName()),ExcelThread::ExcelOperatorType::WriteData,this);
//                        //						threadexlsR->setGroup(groupid);
//                        if(itor != m_BarrelStatus.end()){
//                            QDir dirrecord(dirParent.absolutePath() + QDir::separator() + QStringLiteral("投料记录"));
//                            if(!dirrecord.exists())
//                                dirrecord.mkpath(dirrecord.absolutePath());
//                            QString var = QString("yyyy-MM-dd_hh%1mm%2ss%3");
//                            var = var.arg(QStringLiteral("时"),QStringLiteral("分"),QStringLiteral("秒"));
//                            QFile file(dirrecord.absoluteFilePath(QDateTime::currentDateTime().toString(var) + ".txt"));
//                            file.open(QIODevice::WriteOnly | QIODevice::Text);

//                            QStringList listboxnum = itor.value().valueOfBoxnum;
//                            for(int itt = 0;itt<24;itt++)
//                            {
//                                QMap<int,quint32>::const_iterator it = itor.value().m_data_reale.find(listboxnum.count()>itt?listboxnum.at(itt).toInt():
//                                                                                                                             ui->tableWidget->item(itt,0)->text().toInt());
//                                QString value = "0";
//                                if(it != itor.value().m_data_reale.end())
//                                {
//                                    value = QString::number(QString::number(it.value()).toDouble() * 0.01);
//                                    //                                    tmpmap.insert(itt+1,value);
//                                }
//                                file.write(value.toLatin1().data());
//                                file.write("\n");
//                            }
//                            file.close();
//                            //                            threadexlsR->setWriteDate(tmpmap);
//                        }
//                        //						threadexlsR->start();
//                        break;//NOTE:just match first one.
//                    }
//                    i--;
//                }


////                QByteArray recv_bufbyte=socket->readAll();
////                struct send_head *recv;
////                recv=(struct send_head *)recv_bufbyte.data()+recv_bufbyte.indexOf(0xbb);

//                //                if(recv->cmd==0xf4)//Not right.TODO
//                //				{
//                QMap<int,sendHead>::const_iterator itor = m_BarrelStatus.find(groupid);
//                sendHead shtmp;
//                if(itor != m_BarrelStatus.end()){
//                    //                        m_BarrelStatus.find(groupid).value().cleanDataOfBarrel();
//                    //                        m_BarrelStatus.find(groupid).value().cleanDataOfPutweigh();
//                    shtmp = itor.value();
//                    shtmp.cleanDataOfBarrel();
//                    shtmp.cleanDataOfPutweigh();
//                    m_BarrelStatus.insert(groupid,shtmp);
//                    qDebug()<<"...from serve."<<m_BarrelStatus.find(groupid).value().m_data_barrel.find(1).value();
//                    //				}
//                    qDebug()<<"put weigh success.Get return value from serve.";//<<recv->cmd;

//                    //if not the current.
//                    if(groupid == ui->combGroup->currentText().toInt())
//                        setupTableItem(m_BarrelStatus.find(groupid).value().getBoxValueList());
//                }

//				socket->disconnectFromHost();//just for single thread...
//				socket->waitForDisconnected(500);
//				socket->deleteLater();

//			});
            //! end.
		}
	}
	else{
		qDebug()<<"connect not success. ipadd invaild.";
		return;
	}

//    QMap<int,sendHead>::const_iterator itor = m_BarrelStatus.find(ui->combGroup->currentText().toInt());
//    if(itor != m_BarrelStatus.end()){
//        m_BarrelStatus.find(ui->combGroup->currentText().toInt()).value().cleanDataOfPutweigh();
////        m_BarrelStatus.insert(ui->combGroup->currentText().toInt(),current);
//        m_BarrelStatus.find(ui->combGroup->currentText().toInt()).value().m_hadBarrel = true;
//    }else{
//        qDebug()<<QString("insert error,cant not find the value of current%1").arg(ui->combGroup->currentText());
//    }
	//not define finished

	//Record to sql data.
	RecordToSql(ui->combGroup->currentText().toInt());

	return ;
}

void Widget::ImportData(bool IsAuto)
{
	IsImportDataAuto = IsAuto;
	QString datapath;
	QSettings setting;
	setting.beginGroup("general");
	datapath = setting.value("DefaultSaveDir",QStandardPaths::DataLocation).toString();
	setting.endGroup();
	bool flagErroe = true;

	if(IsAuto){
		QDir dataDir(datapath);
		dataDir.setFilter(QDir::Dirs|QDir::Files|QDir::NoDotAndDotDot);
		dataDir.setSorting(QDir::DirsFirst);

		bool flag = true;

qDebug()<<QStringLiteral("自动导入:")<<dataDir.entryList().count()<<dataDir.absolutePath();

//        foreach(QString str,dataDir.entryList())
		{
//            grouploadstatus.insert(str.toInt(),false);
//            QString Currentpath  = dataDir.absolutePath()+QDir::separator()+ str;;
			QString Currentpath  = dataDir.absolutePath()+QDir::separator() + (ui->combGroup->currentText());

			QDir currentdir(Currentpath);
			currentdir.setFilter(QDir::Files|QDir::NoDotAndDotDot);
			QFileInfoList list = currentdir.entryInfoList();
			int i=list.count();

			qDebug()<<QStringLiteral("自动导入-读取文件:")<<list.count()<<flag<<i<<currentdir.absolutePath();
//            if(flag)
			{
				while(i){
					QFileInfo fileInfo = list.at(i-1);
					QString fileBaseName = fileInfo.fileName();

//                    bool isFile_dat = fileInfo.fileName().endsWith(".xlsx");
//                    if(!isFile_dat)
//                        isFile_dat = fileInfo.fileName().endsWith(".xls");
//                    if (isFile_dat)
					if (fileInfo.completeSuffix().contains("xl"))
					{
						qDebug()<<fileInfo.fileName()<<currentdir.absoluteFilePath(fileInfo.fileName())<<__LINE__;
						fileBaseName=fileInfo.baseName();
						//                    ExcelThread *threadexlsR = new ExcelThread(currentdir.absoluteFilePath(fileInfo.fileName()),ExcelThread::ExcelOperatorType::ReadData,this);
						//                    threadexlsR->setGroup(str.toInt());
						//                    threadexlsR->start();
						//                    connect(threadexlsR,SIGNAL(finishedReadData(int,QMap<int,QString>)),this,SLOT(ImportDataFromThreadFinished(int,QMap<int, QString>)),
						//                            Qt::QueuedConnection);

qDebug()<<QStringLiteral("自动导入-读取数据:")<<fileBaseName<<fileInfo.fileName();

						ExcelEngine *excel = new ExcelEngine(ExcelEngine::ReadWrite,currentdir.absoluteFilePath(fileInfo.fileName()));

						QPair<QMap<int,QString>,QStringList> pairOfBarrelAndBoxNum = excel->ReadDataSheetByODBC(QStringLiteral("投喂标准"));
						QStringList mBoxNum = pairOfBarrelAndBoxNum.second;
						ImportDataFromThreadFinished(ui->combGroup->currentText().toInt(),pairOfBarrelAndBoxNum.first,mBoxNum);
						excel->Close();
						flag = false;
						emit sigChangeBoxSort(mBoxNum);
						qDebug()<<"Import success..."<<mBoxNum;
						break;//NOTE:just match first one.
					}
					i--;
				}
				flagErroe = flag;
			}
//            else{
//				break;//NOTE:just match first one.
//			}
		}
	}
	else {
		QString filename = QFileDialog::getOpenFileName(this, tr("Open File"),datapath);
		qDebug()<<"filename:manual:"<<"filename:"<<filename;
		if(!filename.isEmpty())
		{
			flag = false;
			ExcelEngine *excel = new ExcelEngine(ExcelEngine::ReadWrite,filename);
			if(excel){
				//            QMap<int,QString> map_tmp = excel->ReadDataFromSqlByColumn(false,QStringLiteral("投喂标准"));
				QPair<QMap<int,QString>,QStringList> pairOfBarrelAndBoxNum = excel->ReadDataSheetByODBC(QStringLiteral("投喂标准"));
				QStringList mBoxNum = pairOfBarrelAndBoxNum.second;

				QMap<int,QString> map_tmp = pairOfBarrelAndBoxNum.first;
				ImportDataFromThreadFinished(ui->combGroup->currentText().toInt(),map_tmp,mBoxNum);
				excel->Close();
				emit sigChangeBoxSort(mBoxNum);
			}
		}
	}
	if(flagErroe && IsAuto){
		QMessageBox::information(0,"",QStringLiteral("文件打开失败，请确认文件是否存在."));
		return;
	}
}

void Widget::ImportDataFromThreadFinished(int groupnum,QMap<int, QString> map_xls,QStringList boxnum)
{
	if(map_xls.size())//get data to insert.
    {
		sendHead sh_barrel;
		if(m_BarrelStatus.find(groupnum) != m_BarrelStatus.end()){
			sh_barrel = m_BarrelStatus.find(groupnum).value();
			sh_barrel.insertBarrel(map_xls);
//			sh_barrel.valueOfBoxnum = boxnum;
            sh_barrel.insetBoxValue(boxnum);
		}
		m_BarrelStatus.insert(groupnum,sh_barrel);
//        if(groupnum==ui->combGroup->currentText().toInt())
		{
			QMap<int,QString>::const_iterator itor;
			for(itor = map_xls.constBegin();itor!=map_xls.constEnd();itor ++)
			{
				int groupnum = itor.key();
				if(ui->tableWidget->item(groupnum-1,1)){
					QTableWidgetItem *item = new QTableWidgetItem(QString::number(itor.value().toFloat()));
					item->setTextAlignment(Qt::AlignCenter);
					ui->tableWidget->setItem( groupnum-1 , 1 ,item);
				}
			}
		}
	}
    ui->pushButton_weigh->setEnabled(true);

	//Todo:Test to export the data to the excel
//    ExportDataToExcelExists();
}

void Widget::ExportDataToExcelExists(int group)
{
//    QString filename = QFileDialog::getOpenFileName();//QStringLiteral("H:/QtProject/build/MinGW-debug/海大投料表 - 副本.xlsx");

	QString datapath;
	QSettings setting;
	setting.beginGroup("general");
	datapath = setting.value("DefaultSaveDir",QStandardPaths::DataLocation).toString();
	setting.endGroup();

	QDir dataDir(datapath);
	dataDir.setFilter(QDir::Dirs|QDir::Files|QDir::NoDotAndDotDot);
	dataDir.setSorting(QDir::DirsFirst);

	bool flag = true;
//    foreach(QString str,dataDir.entryList())
	{
		QString Currentpath  = dataDir.absolutePath()+QDir::separator()+ group;;
		QDir currentdir(Currentpath);
		if(currentdir.exists()){
			currentdir.setFilter(QDir::Dirs|QDir::Files|QDir::NoDotAndDotDot);
			QFileInfoList list = currentdir.entryInfoList();
			int i=list.count();
			//        if(flag)
			{
				while(i){
					QFileInfo fileInfo = list.at(i-1);
					QString fileBaseName = fileInfo.fileName();

//					bool isFile_dat = fileInfo.fileName().endsWith(".xlsx") |
//							fileInfo.fileName().endsWith(".xls");
//					if (isFile_dat)
					{
						qDebug()<<fileInfo.fileName()<<currentdir.absoluteFilePath(fileInfo.fileName())<<__LINE__;
						fileBaseName=fileInfo.baseName();

						ExcelThread *threadexls = new ExcelThread(currentdir.absoluteFilePath(fileInfo.fileName())
																  ,ExcelThread::ExcelOperatorType::WriteData,this);

						QMap<int,sendHead>::const_iterator itor = m_BarrelStatus.find(group);
						if(itor != m_BarrelStatus.end()){
							QMap<int,QString> mapTmp;
							for(int i = 1;i<25;i++){
								QMap<int,quint32>::const_iterator itorT = itor.value().m_data_reale.find(i);
								if(itorT != itor.value().m_data_reale.end())
									mapTmp.insert(i,QString::number(itorT.value()*0.01));
								else mapTmp.insert(i,"-");
							}
							threadexls->setWriteDate(mapTmp);
							threadexls->start();
							flag = false;
							break;
						}
					}
					i--;
				}
			}
		}else{
			QString text = "\"" + currentdir.absolutePath() + QStringLiteral("\"\n文件夹内不存在Excel数据文件");
			QMessageBox::information(NULL,QStringLiteral("提示"),text);
		}
//        else{
//            break;
//        }
	}
}

//!
//! \brief Widget::RecordToSql
//! \param groupNum
//! \param map
//! \author vacant
//! \date 2014-09-14
//! \caption 从服务器得到称量值后进行投料所得数据存入SQL中
void Widget::RecordToSql(int groupNum)
{
	if(groupNum<0)
		return;

	//! start to record.
	//Create db.
	QSqlDatabase db=QSqlDatabase::addDatabase("QSQLITE");
//    query.exec(QString("drop table %1").arg( groupNum ));
	//check record directory wheather exists.
	QString datapath = QApplication::applicationDirPath() + "/../data";
	QString filename = QString("%1.db").arg(QDateTime::currentDateTime().toString("yyyyMMdd"));
	QString fullfilename;
	QDir dirDataPath(datapath);
	if(!dirDataPath.exists()){
		dirDataPath.mkpath(datapath);
	}
	fullfilename = dirDataPath.absoluteFilePath(filename);
	if(fullfilename.isEmpty()){
		QMessageBox::information(0,QStringLiteral("数据记录出错"),QStringLiteral("目录创建失败，请以管理员权限重新运行程序.\n"));
		return;
	}
	db.setDatabaseName(fullfilename);
	QSqlQuery query;
	if(db.open()){
		query = QSqlQuery(db);
	}else{
		QMessageBox::information(0,QStringLiteral("数据记录出错"),QStringLiteral("数据记录失败:\n") + db.lastError().text());
	}

	QStringList fieldList = QStringList()<<"groupid"
											 <<"date"
											 <<"time"
											 <<"barrels"
											 <<"weighs";
	QString listofquery = fieldList.first() + " varchar(50)";
	foreach(QString field,fieldList){
		if(field != fieldList.first())
			listofquery.append("," + field + " varchar(250)");
	}
	query.exec(QString("create table %1(%2)").arg(SQLDATARECORDTBNAME,listofquery));
	//insert data to table.
	QString barrelsValue,weighsValue;
	QString listofqueryInsert = fieldList.first();
	foreach(QString field,fieldList){
		if(field != fieldList.first())
			listofqueryInsert.append("," + field);
	}
	//data handle.
	QMap<int,sendHead>::const_iterator itorGroup = m_BarrelStatus.find(groupNum);
	if(itorGroup != m_BarrelStatus.end()){//QMap<int,quint32> m_data_barrel
		QMap<int,quint32>::const_iterator itorBarrel = m_BarrelStatus.find(groupNum).value().m_data_barrel.begin();
		for(itorBarrel;itorBarrel!=m_BarrelStatus.find(groupNum).value().m_data_barrel.end();itorBarrel++){
			if(itorBarrel == m_BarrelStatus.find(groupNum).value().m_data_barrel.begin()){
				barrelsValue.append(QString::number((int)itorBarrel.key()) + "|" + QString::number(itorBarrel.value()*0.01));
			}else{
				barrelsValue.append("," + QString::number((int)itorBarrel.key()) +"|" + QString::number(itorBarrel.value()*0.01));
			}
		}
		QMap<int,quint32>::const_iterator itorWeigh = m_BarrelStatus.find(groupNum).value().m_data_reale.begin();
		for(itorWeigh;itorWeigh!=m_BarrelStatus.find(groupNum).value().m_data_reale.end();itorWeigh++){
			if(itorWeigh == m_BarrelStatus.find(groupNum).value().m_data_reale.begin()){
				weighsValue.append(QString::number((int)itorWeigh.key()) + ":" + QString::number(itorWeigh.value()*0.01));
			}else{
				weighsValue.append("," + QString::number((int)itorWeigh.key())+":" + QString::number(itorWeigh.value()*0.01));
			}
		}
	}

	query.prepare(QString("insert into %1 (%2) values (:groupid,:date,:time,:barrels,:weighs)").arg(SQLDATARECORDTBNAME,listofqueryInsert));
	query.bindValue(":groupid",QString::number(groupNum));
	query.bindValue(":date",QDateTime::currentDateTime().toString("yyyyMMdd"));
	query.bindValue(":time",QDateTime::currentDateTime().toString("hh:mm:ss"));
	query.bindValue(":barrels",barrelsValue);
	query.bindValue(":weighs", weighsValue);
	query.exec();
}


//protected virtual function Handle
void Widget::closeEvent(QCloseEvent *event)
{
	QSettings setting;

	emit onCloseWidget();
	qDebug()<<this->findChild<FormSetting*>()<<__LINE__;

	int tipscount = 0;
	setting.beginGroup("AppData/Operate");
	tipscount = setting.value("showTips",0).toInt();
	setting.endGroup();
	setting.beginGroup("GroupData");
	foreach(QString text,setting.childGroups())
		setting.setValue((QString("%1/States").arg(text)),false);
	setting.endGroup();

	if(system_tray && tipscount<3 ){
		system_tray->showMessage(QStringLiteral("提示!"),QStringLiteral("程序最小化到此"));
		setting.beginGroup("AppData/Operate");
		setting.setValue("showTips",++tipscount);
		setting.endGroup();
	}

	setting.setValue("AppData/geometry",saveGeometry());

	if(setting.value("AppData/CloseAppNotQuit",true).toBool())
	{
		event->ignore();
		this->hide();
	}
	else {
		event->accept();
		qApp->quit();
	}
}

void Widget::resizeEvent(QResizeEvent *event)
{
//    ui->tableWidget->horizontalHeader()->resize();
	ui->tableWidget->horizontalHeader()->resize(ui->tableWidget->size().width(),ui->tableWidget->horizontalHeader()->height());

    emit sig_resize(event);
    event->accept();
}

bool Widget::eventFilter(QObject *obj, QEvent *event)
{
	if(obj == ui->tableWidget){
		QKeyEvent *keyevent = static_cast<QKeyEvent*>(event);
		if(keyevent->key() == Qt::Key_Delete || keyevent->key() == Qt::Key_Backspace) {
			if(ui->tableWidget->selectedItems().count()){
				foreach(QTableWidgetItem *item,ui->tableWidget->selectedItems()){
					if(item->column() == 1){//只能删除第二列的数据
						if(!item->text().isEmpty())
							item->setText("");
					}else{
						return true;
					}
					delete item;
					item = NULL;
				}
			}
		}
//        if(keyevent->key() == Qt::Key_Control && keyevent->key()==Qt::Key_C){
//            ui->tableWidget->selectColumn(2);
//            copyTable();
//        }
	}

    if(obj == ui->btn_GloHome){
//        if(event->type() == QEvent::Enter){
//            ui->btn_GloHome->setIcon(QIcon(":/res/images/returnBtnhov.png"));
//        }else if(event->type() == QEvent::Leave){
//            ui->btn_GloHome->setIcon(QIcon(":/res/images/returnBtnnor.png"));
//        }
    }
	return QWidget::eventFilter(obj,event);
}


void Widget::mousePressEvent(QMouseEvent *event)
{
	offset = event->globalPos() - pos();
	event->accept();
}

void Widget::mouseMoveEvent(QMouseEvent *event)
{
	move(event->globalPos() - offset);
	event->accept();
}

void Widget::mouseReleaseEvent(QMouseEvent *event)
{
	offset = QPoint();
	event->accept();
}

///Old Data....-------------------------------------------------------------------------------------------------------------------------
void Widget::connect_Close()
{
}

void Widget::SetWidgetGrowEffect(QWidget *widget)
{
    GlowEffect *effect = new GlowEffect(widget);
    effect->setRadius(3);
    effect->setGlowColor(Qt::white);
    widget->setGraphicsEffect(effect);
}

void Widget::initHomeBtnEffect()
{
    //add resources
//    ui->btn_HomeaddGroup->setIcon(QIcon(":/res/images/btn_addgroup.gif"));
    ui->btn_GloHome->setVisible(false);
    ui->btn_GloStartPut->setVisible(false);

    SetWidgetGrowEffect(ui->btn_HomeaddGroup);
    SetWidgetGrowEffect(ui->btn_HomeaddRecord);
//    SetWidgetGrowEffect(ui->btn_HomesetDly);
//    SetWidgetGrowEffect(ui->btn_HomestartPut);
    SetWidgetGrowEffect(ui->btn_HomestartWeigh);
    SetWidgetGrowEffect(ui->btn_HomeViewPut);
    SetWidgetGrowEffect(ui->btn_HomeSetting);

    //add title of button
    QStringList list = QStringList()<<QStringLiteral("添加分组")<<QStringLiteral("数据导入")<<QStringLiteral("开始投料")<<QStringLiteral("查看记录")<<QStringLiteral("软件设置");
    ui->btn_HomeaddGroup->setText(list.at(0));
    ui->btn_HomeaddRecord->setText(list.at(1));
    ui->btn_HomestartWeigh->setText(list.at(2));
    ui->btn_HomeViewPut->setText(list.at(3));
    ui->btn_HomeSetting->setText(list.at(4));
    ui->btn_HomeaddGroup->setToolTip(list.at(0));
    ui->btn_HomeaddRecord->setToolTip(list.at(1));
    ui->btn_HomestartWeigh->setToolTip(list.at(2));
    ui->btn_HomeViewPut->setToolTip(list.at(3));
    ui->btn_HomeSetting->setToolTip(list.at(4));

    connect(ui->btn_GloStartPut,&QToolButton::clicked,[=]{
        for(int i = 0;i<ui->treeWidget->topLevelItemCount();i++){
            QTreeWidgetItem * item  = ui->treeWidget->topLevelItem(i);
            auto *item_widget = qobject_cast<FormItemWidgetGroup*>(ui->treeWidget->itemWidget(item,0));
            if(item_widget){
                if(!item_widget->getEnable()){
                    item->setExpanded(false);
                }else{
                    emit item_widget->sig_startPut();
                    //load data from sql db.
//                    if(!item_widget->IsLoadSubItem)//只允许第一次展开时加载->toolBox widget remove problem.
//                    {
//                        FormRecordControl *rc_widget = qobject_cast<FormRecordControl*>(ui->treeWidget->itemWidget(item->child(0),0));
//                        item_widget->IsLoadSubItem = rc_widget->loadDataFromSql(item_widget->Data());
//    //                    item_widget->IsLoadSubItem = rc_widget->loadDataFromSql(item_widget->getTitle());
//    //                    item_widget->IsLoadSubItem = true;
//                        if(!item_widget->IsLoadSubItem){
//                            ui->treeWidget->itemWidget(item,0)->setEnabled(false);
//                        }
//                    }
                }
            }
        }
    });

    connect(ui->btn_HomeaddRecord,&QToolButton::clicked,[=]{
        WinMgr.showRecordControl();
    });

    connect(ui->btn_HomeaddGroup,&QToolButton::clicked,[=]{
//        WinMgr.showAddGroup();//not use it now.
        setupSettingForm(this);//TODO:clos it had problem.
    });

    connect(ui->btn_HomeSetting,&QToolButton::clicked,[=]{
        setupSettingForm(this);
    });

    connect(ui->btn_HomeViewPut,&QToolButton::clicked,[=]{
        WinMgr.showViewRecord();
    });

    connect(ui->btn_HomestartWeigh,&QToolButton::clicked,[=]{
        //treewidget init
//        initTreeWidget();

        ui->switchWin->setCurrentWidget(ui->page_Group);
    });
}

void Widget::initHomeButton()
{
//    ui->btn_GloHome->setVisible(false);
    ui->btn_GloHome->installEventFilter(this);

    //init effect
    initHomeBtnEffect();

    initTreeWidget();


    //add connect
    connect(ui->btn_GloHome,&QToolButton::clicked,[=]{
        ui->switchWin->setCurrentWidget(ui->page_Home);
        ui->switchWin_Right->setCurrentWidget(ui->page_Empty);
        ui->widget_RightSide->setVisible(false);
        setMinimumWidth(870);
        adjustSize();
    });
}

void Widget::initTreeWidget()
{
    for(int i = 0;i<ui->treeWidget->topLevelItemCount();i++)
        ui->treeWidget->takeTopLevelItem(i);
    ui->treeWidget->clear();
    ui->treeWidget->setAlternatingRowColors(true);
    ui->treeWidget->setHeaderHidden(true);
    ui->treeWidget->setSelectionMode(QAbstractItemView::ExtendedSelection);


    QMapIterator<int,QString> itor_ipadd(_GroupIpList);//?????
    while(itor_ipadd.hasNext()){
        itor_ipadd.next();
        QTreeWidgetItem *item = new QTreeWidgetItem(ui->treeWidget);
        FormItemWidgetGroup *itemsubWidget = new FormItemWidgetGroup(
                    QStringList()<<QStringLiteral("组号")<<QString::number(itor_ipadd.key()),ui->treeWidget);
        itemsubWidget->setCheck(true);
        itemsubWidget->setValue(QStringList()<<QStringLiteral("IP地址")<<(itor_ipadd.value()));
        itemsubWidget->updateDateTime();

        connect(itemsubWidget,&FormItemWidgetGroup::sig_EnableItem,[=](bool flag){
            if(item){
                flag?item->setChildIndicatorPolicy(QTreeWidgetItem::ShowIndicator):
                     item->setChildIndicatorPolicy(QTreeWidgetItem::DontShowIndicator);
                if(flag)
                    item->setExpanded(false);
            }
        });

        connect(&WinMgr,&WinManager::sig_changIP,[=]{
            QSettings setting;
            setting.beginGroup("GroupData");
            foreach(QString str,setting.childGroups()){
                if(str == QString::number(itor_ipadd.key())){
                    itemsubWidget->setIp(setting.value(QString("%1/IpAdd").arg(str)).toString());
                }
            }
        });

        connect(itemsubWidget,&FormItemWidgetGroup::sig_startPut,[=](){
//            if(data.getStartTime()<QDateTime::currentDateTime().time()){
//                qDebug()<<"start time less current time.";
//                QMessageBox::about(0,"",QStringLiteral("投放时间小于当前时间，须大于当前时间（分钟），请确认设置正确再重试!"));
////                item->setSelected(true);//批量操作时
//                ui->treeWidget->setCurrentItem(item);
//                return;
//            }

            if(item){
                if(item->childCount()){
                    if(itemsubWidget->getEnable()){//check current item is avilable
                        FormRecordControl *rc_widget = qobject_cast<FormRecordControl*>(ui->treeWidget->itemWidget(item->child(0),0));
                        rc_widget->setParentWidget(itemsubWidget);

                        //load data from sql db.
                        if(!itemsubWidget->IsLoadSubItem)
                        {
                            itemsubWidget->IsLoadSubItem = rc_widget->loadDataFromSql(itemsubWidget->Data());//prepare data and insert to GroupData struct.
                            if(!itemsubWidget->IsLoadSubItem){
                                ui->treeWidget->itemWidget(item,0)->setEnabled(false);
                            }
                        }
                        //show right side.
                        if(ui->switchWin_Right->currentWidget() != ui->page_Right_Status){
                            ui->switchWin_Right->setCurrentWidget(ui->page_Right_Status);
                            ui->switchWin_Right->setVisible(true);
//                            ui->switchWin_Right->setVisible(false);//暂时不显示
                        }
                        //put operation.->TODO:test.
                        rc_widget->putWeigh(itemsubWidget->Data());
                        itemsubWidget->setStatus(" ");
                        //第几次?
                        itemsubWidget->setStatus(rc_widget->GroupData().currentTable() /*+ QString("%1").arg(rc_widget->GroupData())num*/);
                        //update widget of right widget status
                        groupButtonStatus(itemsubWidget->getGroupNum(),emPS_Start);
                    }
                }
            }
        });

        ui->treeWidget->setItemWidget(item,0,itemsubWidget);

        //subItem load when double clicked or Show indicator.
        QTreeWidgetItem *item_sub = new QTreeWidgetItem;
        item->addChild(item_sub);
        ui->treeWidget->setItemWidget(item_sub,0,new FormRecordControl(FormRecordControl::RCT_PutWeigh,ui->treeWidget));
        auto *subItemWidget = qobject_cast<FormRecordControl*>(ui->treeWidget->itemWidget(item_sub,0));
        subItemWidget->setParentWidget(itemsubWidget);
        subItemWidget->setGroupNum(QString::number(itor_ipadd.key()));
        subItemWidget->setGroupData(itemsubWidget->Data());
        ui->treeWidget->insertTopLevelItem(0,item);

        connect(itemsubWidget,&FormItemWidgetGroup::sig_dataChange,[=](QString str,QString value){
//            qDebug()<<subItemWidget;
        });
    }

    connect(ui->treeWidget,&QTreeWidget::itemPressed,[=]
    (QTreeWidgetItem * item, int){
        if(!item->childCount()){
            item->setSelected(false);
        }
    });

    connect(ui->treeWidget,&QTreeWidget::itemExpanded,[=](QTreeWidgetItem * item){
        auto *item_widget = qobject_cast<FormItemWidgetGroup*>(ui->treeWidget->itemWidget(item,0));
        if(item_widget){
            if(!item_widget->getEnable()){
                item->setExpanded(false);
            }else{
                //load data from sql db.
                if(!item_widget->IsLoadSubItem)//只允许第一次展开时加载->toolBox widget remove problem.
                {
                    FormRecordControl *rc_widget = qobject_cast<FormRecordControl*>(ui->treeWidget->itemWidget(item->child(0),0));
                    rc_widget->setParentWidget(item_widget);
                    item_widget->IsLoadSubItem = rc_widget->loadDataFromSql(item_widget->Data());
//                    item_widget->IsLoadSubItem = rc_widget->loadDataFromSql(item_widget->getTitle());
//                    item_widget->IsLoadSubItem = true;
                    if(!item_widget->IsLoadSubItem){
                        ui->treeWidget->itemWidget(item,0)->setEnabled(false);
                    }
                }
            }
        }
    });

    connect(ui->treeWidget,&QTreeWidget::itemClicked,[=](QTreeWidgetItem *item, int column){//load data.
        if(item->childCount())
            if(ui->treeWidget->itemWidget(item,column)){
//                FormItemWidgetGroup *itemWidget = qobject_cast<FormItemWidgetGroup*>(ui->treeWidget->itemWidget(item,column));
//                itemWidget->loadDataFromSql();

                //sub item.
                if(!ui->treeWidget->currentItem()->child(0)->childCount()){
//                    FormRecordControl *itemsubWidget = qobject_cast<FormRecordControl*>(ui->treeWidget->itemWidget(ui->treeWidget->currentItem()->child(0),column));
//                    if(itemsubWidget){
//                        itemsubWidget->loadDataFromSql();
//                    }
                }
            }
    });
//    connect(ui->treeWidget,&QTreeWidget::currentItemChanged,[=]
//            (QTreeWidgetItem * current, QTreeWidgetItem * /*previous*/){
//        if(current->childCount()){

//        }
    //    });
}

void Widget::groupButtonStatus(QString group, em_PutStatus state)
{
    foreach(QToolButton *btn,ui->groupBox->findChildren<QToolButton*>())   {
        QRegExp reg("([\\d]{1,}).*");
        if(btn){
            if(reg.indexIn(btn->text()) != -1){
                if(group==reg.cap(1)){
                    QIcon icon(":/res/global/app.png");
                    switch(state){
                    case 0:
                        icon = QIcon("");
                        break;
                    default:
                        break;
                    }
                    btn->setIcon(icon);
                    break;
                }
            }
        }
    }
}

void Widget::sltcbGrpChange(const QString &text)
{
    for(int i = 0; i<ui->treeWidget->topLevelItemCount();i++){
        ui->treeWidget->setItemSelected(ui->treeWidget->topLevelItem(i),false);
        if(qobject_cast<FormItemWidgetGroup*>(ui->treeWidget->itemWidget(ui->treeWidget->topLevelItem(i),0))->getGroupNum().toInt()
                == text.toInt()){
            ui->treeWidget->setItemSelected(ui->treeWidget->topLevelItem(i),true);
            ui->treeWidget->topLevelItem(i)->setExpanded(true);
        }else{
            if(ui->treeWidget->topLevelItem(i)->isExpanded()){
                ui->treeWidget->topLevelItem(i)->setExpanded(false);
            }
        }
    }
//	ui->states_group_IPSet->setText(ui->combGroup->itemData(ui->combGroup->currentIndex()).toString());

//	QSettings setting;
//	setting.beginGroup("GroupData");
//	bool flag_ipstates = setting.value(QString("%1/States").arg(text)).toBool();
//	setting.endGroup();
//	ui->pushButton_link->setEnabled(flag_ipstates);
//	ui->pushButton_close->setEnabled(!flag_ipstates);
//	ui->pushButton_weigh->setEnabled(flag_ipstates);

//    qDebug()<<m_BarrelStatus.find(ui->combGroup->currentText().toInt()).value().m_hadPutweigh
//            <<m_BarrelStatus.find(ui->combGroup->currentText().toInt()).value().m_hadBarrel
//            <<ui->pushButton_weigh->isEnabled()<<ui->pushButton_put->isEnabled();

////    ui->pushButton_weigh->setEnabled(!ui->pushButton_put->isEnabled());
////	ui->pushButton_put->setEnabled(m_BarrelStatus.find(ui->combGroup->currentText().toInt()).value().m_hadPutweigh);
////    ui->pushButton_weigh->setEnabled(!m_BarrelStatus.find(ui->combGroup->currentText().toInt()).value().m_hadBarrel);
////    ui->pushButton_put->setEnabled(m_BarrelStatus.find(ui->combGroup->currentText().toInt()).value().m_hadPutweigh);

//	//! Data Handle.
//	QString datapath;
//	setting.beginGroup("general");
//	datapath = setting.value("DefaultSaveDir",QStandardPaths::DataLocation).toString();
//	setting.endGroup();
//	QDir dataDir(datapath);
//	dataDir.setFilter(QDir::Dirs|QDir::Files|QDir::NoDotAndDotDot);
//	dataDir.setSorting(QDir::DirsFirst);

//	int stateData = setting.value("general/DataImportHandle",QByteArray("-1")).toByteArray().toInt();
//	QMap<int,sendHead>::const_iterator itor = m_BarrelStatus.find(ui->combGroup->currentText().toInt());
//	if(stateData>0)//if stateDate == 0, should import data by user handle.
//	{
//		if(itor != m_BarrelStatus.end()){
//			if(!itor.value().m_hadBarrel)
//				if(IsImportDataAuto)
//				{
//					QString Currentpath  = dataDir.absolutePath()+QDir::separator()+ ui->combGroup->currentText();
//					QDir currentdir(Currentpath);
//					currentdir.setFilter(QDir::Dirs|QDir::Files|QDir::NoDotAndDotDot);
//					QFileInfoList list = currentdir.entryInfoList();
//					int i=list.count();
//					while(i){
//						QFileInfo fileInfo = list.at(i-1);
//						QString fileBaseName = fileInfo.fileName();

//						bool isFile_dat = fileInfo.fileName().endsWith(".xlsx") |
//								fileInfo.fileName().endsWith(".xls");
//						if (isFile_dat) {

//							fileBaseName=fileInfo.baseName();
//							ExcelEngine *excel = new ExcelEngine(ExcelEngine::ReadWrite,currentdir.absoluteFilePath(fileInfo.fileName()));
//							QPair<QMap<int,QString>,QStringList> pairOfBarrelAndBoxNum = excel->ReadDataSheetByODBC(QStringLiteral("投喂标准"));
//							QStringList mBoxNum = pairOfBarrelAndBoxNum.second;
//							ImportDataFromThreadFinished(ui->combGroup->currentText().toInt(),pairOfBarrelAndBoxNum.first,mBoxNum);

//                            //end test.
//							excel->Close();
//							qDebug()<<"Get mBoxNum"<<mBoxNum;
//							emit sigChangeBoxSort(mBoxNum);
//							break;//NOTE:just match first one.
//						}
//						i--;
//					}
//				}
//		}
//		//! end Handle Data.
//	}
//	else{
////        if(itor != m_BarrelStatus.end())
////            if(!itor.value().m_hadBarrel)
//		;
//	}

//	if(m_BarrelStatus.find(ui->combGroup->currentText().toInt())!=m_BarrelStatus.end()){
//        setupTableItem(m_BarrelStatus.find(ui->combGroup->currentText().toInt()).value().getBoxValueList());//有数据时不刷新表格数据内容,继续保留,直至投料完成（已有对功能进行判断处理）

//		if(m_BarrelStatus.find(ui->combGroup->currentText().toInt()).value().m_hadPutweigh)
//			checkItemValue();//已得实际称量值,进行数据判断
//        //if set putweigh time then update ui widget.
//        if(!m_BarrelStatus.find(ui->combGroup->currentText().toInt()).value().getPutweighTime().isNull()){
//            qDebug("had set putweigh time...");
//            ui->states_group_timeSet_Remain->setText(m_BarrelStatus.find(ui->combGroup->currentText().toInt()).value().getPutweighTime().toString("yyyy-MM-dd hh:mm:ss"));
//            //set again ui enable of puweigh
//            ui->pushButton_weigh->setEnabled(false);
//            ui->pushButton_put->setEnabled(false);
//        }else{
//            ui->states_group_timeSet_Remain->setText(QDateTime::currentDateTime().toString("yyyy-MM-dd 00:00:00"));
//            ui->pushButton_put->setEnabled(m_BarrelStatus.find(ui->combGroup->currentText().toInt()).value().m_hadPutweigh);
//            ui->pushButton_weigh->setEnabled(!ui->pushButton_put->isEnabled());
//        }

//    }
}

void Widget::sltcbTblCellChange(int row, int column)
{
	if(!flagSortTable)
	{
		if(column == 1){//只对第二列数据进行处理
			QMap<int,sendHead>::const_iterator itor = m_BarrelStatus.find(ui->combGroup->currentText().toInt());
			if(itor == m_BarrelStatus.end()){//if it's new data.
				m_BarrelStatus.insert(ui->combGroup->currentText().toInt(),sendHead());
			}else
			{
				QString str = ui->tableWidget->item(row,column)->text();
				m_BarrelStatus.find(ui->combGroup->currentText().toInt()).value().insertSingleBarrel(ui->tableWidget->item(row,0)->text().toInt(),str);
			}
		}
	}
}

bool Widget::connectDB()
{
	db=QSqlDatabase::addDatabase("QSQLITE");
  //  QString runPath = QCoreApplication::applicationDirPath().append("mytest.db");
	db.setDatabaseName("mytest.db");
	if(!db.open())
	{
		return false;
	}else{
		return true;
	}
}

bool Widget::cheack_value(QString str)
{
	if(str.isEmpty())
	{
		return true;
	}
 //   QString pattern("^(([0-9]+\.[0-9]*[1-9][0-9]*)|([0-9]*[1-9][0-9]*\.[0-9]+)|([0-9]*[1-9][0-9]*))$");
 //   QString pattern("^(([0-9]+.[0-9]*[1-9][0-9]*)|([0-9]*[1-9][0-9]*.[0-9]+)|([0-9]*[1-9][0-9]*))$");
	QString pattern("[0-9]+.[0-9]|[0-9]+");
	QRegExp rx(pattern);
	return rx.exactMatch(str);
}

void Widget::Weigh_item_cheack(QTableWidgetItem * /*item*/)
{
//    if(item->column()==2){
//        if(!cheack_value(item->text()))
//        {
//            QMessageBox::warning(this, "警告", "输入不符合标准", QMessageBox::Ok, QMessageBox::Ok);
//            item->setText("0");
//            return;
//        }
//       if(item->text().toFloat()>99.9)
//       {
//           QMessageBox::warning(this, "warning", "输入值超出称量范围", QMessageBox::Ok, QMessageBox::Ok);
//           item->setText("0");
//       }
//           return;
//    }
}

quint16 Widget::GetCheckSum (void *data, quint16 len)
{
	quint32 cksum = 0;
	quint16 *p = (quint16*)data;
	while (len > 1)
	{
	cksum += *p++;
	len -=2;
	}
	if (0 != len)
	{
	   cksum += *(quint8 *)p;
	}
	cksum = (cksum >> 16) + (cksum & 0xffff);
	cksum += (cksum >>16);
	return ~cksum;
}

void Widget::connect_Successful()
{
}

void Widget::recv_data(QTcpSocket *client_tcp)
{
	qDebug()<<"recv_data:"<<client_tcp<<tcpSocketHash.find(ui->combGroup->currentText().toInt()).value();
//    if(client_tcp != NULL)
	if(tcpSocketHash.find(ui->combGroup->currentText().toInt()) != tcpSocketHash.end())
	{
		 QByteArray recv_buf;
		// recv_buf=client_tcp->readAll();
		// struct send_head  *recv;
		// recv=(struct send_head *)recv_buf.data()+recv_buf.indexOf(0xbb);
		//qDebug()<<client_tcp->readAll().toHex();
		recv_buf=tcpSocketHash.find(ui->combGroup->currentText().toInt()).value()->readAll();
qDebug()<<QStringLiteral("接收到的数据")<<recv_buf.toHex()<<tcpSocketHash.find(ui->combGroup->currentText().toInt()).value()->isOpen()
		  <<tcpSocketHash.find(ui->combGroup->currentText().toInt()).value()->isValid()<<
			tcpSocketHash.find(ui->combGroup->currentText().toInt()).value()->isReadable()
			<<tcpSocketHash.find(ui->combGroup->currentText().toInt()).value()->isWritable();
		struct send_head *recv;
		float volue;
		recv=(struct send_head *)recv_buf.data()+recv_buf.indexOf(0xbb);
		if(recv->cmd==0xff){
			for(int i=1;i<=24;i++)
			{
				volue=(float)recv->data[i-1]/100;
				item = new QTableWidgetItem(QString::number(volue));
				ui->tableWidget->setItem(i-1,3,item);
				if(recv->data[i-1]-buf.data[i-1]>10)
				{
					ui->tableWidget->item(i-1,0)->setBackgroundColor(QColor(Qt::red));
					ui->tableWidget->item(i-1,1)->setBackgroundColor(QColor(Qt::red));
					ui->tableWidget->item(i-1,2)->setBackgroundColor(QColor(Qt::red));
					ui->tableWidget->item(i-1,3)->setBackgroundColor(QColor(Qt::red));
					err[i-1]=false;
					flag=true;
				}
				if( recv->data[i-1]<buf.data[i-1])
				{
					ui->tableWidget->item(i-1,0)->setBackgroundColor(QColor(Qt::red));
					ui->tableWidget->item(i-1,1)->setBackgroundColor(QColor(Qt::red));
					ui->tableWidget->item(i-1,2)->setBackgroundColor(QColor(Qt::red));
					ui->tableWidget->item(i-1,3)->setBackgroundColor(QColor(Qt::red));
					err[i-1]=false;
					flag=true;
				}
				if(recv->data[i-1]==0xffffffff){
					item = new QTableWidgetItem(QString("离线了"));
					ui->tableWidget->setItem(i-1,3,item);
					ui->tableWidget->item(i-1,0)->setBackgroundColor(QColor(Qt::red));
					ui->tableWidget->item(i-1,1)->setBackgroundColor(QColor(Qt::red));
					ui->tableWidget->item(i-1,2)->setBackgroundColor(QColor(Qt::red));
					ui->tableWidget->item(i-1,3)->setBackgroundColor(QColor(Qt::red));
				}
				item->setFlags(item->flags() & (~Qt::ItemIsEditable));
				item->setTextAlignment(Qt::AlignHCenter | Qt::AlignVCenter);
            }
			if(flag){
				memset(&buf,0,sizeof(buf));
				buf.head=0xbb;
				buf.cmd=0xf3;
				for(int i=0;i<24;i++){
					if(!err[i]){
						buf.data[i]=0xffffffff;
					}
				}
				buf.fcc=GetCheckSum(&buf,sizeof(buf)-sizeof(quint32));
				tcpSocketHash.find(ui->combGroup->currentText().toInt()).value()->write(QByteArray::fromRawData((char *)&buf,sizeof(buf)));
				//  this->display();
			}
			ui->pushButton_put->setEnabled(true);
		}
		if(recv->cmd==0xf4){
;
		}

	}
}


void Widget::display()
{
	qDebug()<<QByteArray::fromRawData((char *)&buf,sizeof(buf)).toHex();
}

//void Widget::on_pushButton_close_clicked()//已有定义
//{
//    ui->pushButton_link->setEnabled(true);
//    client_tcp->close();
//    client_tcp->abort();
// //   ui->tableWidget->item(0,0)->setBackgroundColor(QColor(Qt::red));
//}

void Widget::write_xls()
{
	QString filename=QDateTime::currentDateTime().toString("yyyy-MM-dd")+tr("投放记录.xls");
	QFile file(QString("../")+filename);
	if(!file.open(QIODevice::ReadWrite|QIODevice::Text))
	{
		QMessageBox::warning(this, "警告", "创建文件失败", QMessageBox::Ok, QMessageBox::Ok);
		return;
	}

	QSqlQuery query;
	QString str=QString("select num,formula,strftime('%H:%M',get_Date),volume from fish where flag='B' and get_date>datetime('%1','start of day');") .arg(QDateTime::currentDateTime().toString("yyyy-MM-dd"));
//   // query.prepare("select * from fish where get_date < :time;");
//  query.prepare("select num,formula,strftime('%H:%M',get_Date),volume from fish where flag='B' and get_date<datetime(':time','start of day');");
//  // query.bindValue(":time",QDateTime::currentDateTime().toString("yyyy-MM-dd hh:mm:ss"));
//    query.bindValue(":time",QDateTime::currentDateTime().toString("yyyy-MM-dd"));
//    if(!query.execBatch())
//        qDebug()<<"被调用了"<<QDateTime::currentDateTime().toString("yyyy-MM-dd");
	if(!query.exec(str))
	{
		QMessageBox::warning(this, "警告", "数据库查询失败", QMessageBox::Ok, QMessageBox::Ok);
	}
	QTextStream out(&file);
	out<<QString("桶号")<<"\t"<<QString("配方")<<"\t"<<QString("投料时间")<<"\t"<<QString("投放量(g)")<<"\n";

	while(query.next())
	{
		out<<query.value(0).toString()<<"\t"<<query.value(1).toString()<<"\t"<<query.value(2).toString()<<"\t"<<query.value(3).toString()<<"\n";
		//qDebug()<<query.value(0).toString()<<"\t"<<query.value(1).toString()<<"\t"<<query.value(2).toString()<<"\t"<<query.value(3).toString()<<"\n";
	}
}

void Widget::insert_data(int num, QString Formula, float lg,QString flag)
{
	QSqlQuery query;
	query.prepare("insert into fish values(:num,:Formula,:lg,datetime('now','localtime'),:flag)");
	query.bindValue(":num",num);
	query.bindValue(":Formula",Formula);
	query.bindValue(":lg",lg);
	query.bindValue(":flag",flag);
	if(!query.exec())
	{
		QMessageBox::warning(this, "警告", "插入数据失败", QMessageBox::Ok, QMessageBox::Ok);
	}
}
void Widget::on_pushButton_getinfo_clicked()
{
	this->write_xls();
}


//Style setting...
void Widget::stylize(QString classname,QWidget *widget)
{
#ifdef Q_OS_WIN
	if (QtWin::isCompositionEnabled()) {
		QtWin::extendFrameIntoClientArea(widget, -1, -1, -1, -1);
		widget->setAttribute(Qt::WA_TranslucentBackground, true);
		widget->setAttribute(Qt::WA_NoSystemBackground, false);
		widget->setStyleSheet(QString("%1 { background: transparent; }").arg(classname));
	} else {
		QtWin::resetExtendedFrame(widget);
		widget->setAttribute(Qt::WA_TranslucentBackground, false);
		widget->setStyleSheet(QString("%2 { background: %1; }").arg(QtWin::realColorizationColor().name(),classname));
	}
#endif
}

void Widget::on_switchWin_currentChanged(int )
{
    if(ui->switchWin->currentWidget() != ui->page_Home){
        QTimer *timeAnimation = new QTimer(this);
        QPropertyAnimation *animation = new QPropertyAnimation(ui->widget_RightSide, "geometry");
        connect(timeAnimation,SIGNAL(),this,SLOT());

        connect(timeAnimation,&QTimer::timeout,[=]{
            timeAnimation->stop();
//            ui->widget_RightSide->setVisible(true);
            animation->setDuration(2000);//速度越小越快
            animation->setStartValue(QRect(ui->widget_RightSide->pos() + QPoint(ui->widget_RightSide->width(),0),ui->widget_RightSide->size()));
            animation->setEndValue(QRect(ui->widget_RightSide->pos(),ui->widget_RightSide->size()));
//            animation->setEasingCurve(QEasingCurve::OutBack);//outback缓慢降落
//            animation->setEasingCurve(QEasingCurve::OutBounce);//outbounce有一个缓冲的现象
            animation->setEasingCurve(QEasingCurve::OutQuint);//outcirc和outback差不多
//            animation->setEasingCurve(QEasingCurve::OutInQuart);
            animation->start();
            connect(animation,&QPropertyAnimation::finished,[=]{
                animation->stop();
                animation->deleteLater();
            });
            timeAnimation->deleteLater();
        });
//        timeAnimation->start(200);
        if(ui->btn_GloHome){
            ui->btn_GloHome->setVisible(true);
            ui->btn_GloStartPut->setVisible(true);
        }
        ui->switchWin->setCurrentWidget(ui->page_Group);
        ui->widget_RightSide->setVisible(true);
        ui->switchWin_Right->setVisible(false);
    }else{
        if(ui->btn_GloHome){
            ui->btn_GloHome->setVisible(false);
            ui->btn_GloStartPut->setVisible(false);
        }
        ui->switchWin->setCurrentWidget(ui->page_Home);
        ui->widget_RightSide->setVisible(false);
    }
}
